from django.shortcuts import render,redirect
from .models import  Article,Author
from django.contrib.auth.models import User
from django.core.paginator import Paginator

def index(request):
    list=Article.objects.all()
    paginator=Paginator(list,3)
    x=request.GET.get("page",'1')
    try:
        x=int(x)
        if x<0:
            x=1
    except Exception as e:
        x=1
    pagex=paginator.get_page(x)
    pagex=pagex.object_list
    return render(request,'index.html', {"pagex":pagex})

def add_article(request):
    if request.method=="GET":
        author=Author.objects.all()
        return render(request, 'add_article.html', {"author": author})
    if request.method=="POST":
        name=request.POST.get("name")
        content=request.POST.get("content")
        banben=request.POST.get("banben")
        author=request.POST.get("author")
        article=Article(name=name,content=content,banben=banben,author_id=author)
        article.save()
        return redirect('index')

def def_article(request,articleid):
    article=Article.objects.get(id=articleid)
    article.delete()
    return redirect('index')

def edit_article(request,articleid):
    if request.method=="GET":
        article=Article.objects.get(id=articleid)
        return render(request,'edit_article.html',{"article":article})
    if request.method=="POST":
        name=request.POST.get("name")
        content=request.POST.get("content")
        banben=request.POST.get("banben")
        author=request.POST.get("author")
        article=Article.objects.get(id=articleid)
        article.name=name
        article.content=content
        article.banben=banben
        article.author_id=author
        article.save()
        return redirect('index')